package leetcode;

public class LC48 {
    TreeNode ans = null;

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null && (root == p || root == q)) left = root;
        else if (right == null && (root == p || root == q)) right = root;

        if (left != null && right != null && ans == null) {
            ans = root;
            return ans;
        } else if (left != null && right == null) return left;
        else return right;
    }
}
